package com.shi.vueblog.shiro;

import com.shi.vueblog.entity.User;
import com.shi.vueblog.service.UserService;
import com.shi.vueblog.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;

    public boolean supports(AuthenticationToken token){
        return token instanceof JwtToken;
    }

    //获取用户信息吧，权限信息返回给shiro
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //进行身份认证的时候需要
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwt =(JwtToken)token;
        log.info("jwtToken----------------"+jwt);
            String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();
        User user = userService.getById(Long.parseLong(userId));
        if (user == null){
            throw new UnknownAccountException("用户不存在");
        }
        if (user.getStatus() == -1){
            throw new LockedAccountException("账号被锁定");
        }
        AccountProfile accountProfile=new AccountProfile();
        BeanUtils.copyProperties(user,accountProfile);
        log.info("profile----------------->{}", accountProfile.toString());
        return new SimpleAuthenticationInfo(accountProfile, jwt.getCredentials(), getName());

    }
}
